package com.multition.demo03;

import java.util.HashMap;
import java.util.Map;

/**
 * 多例模式
 */
public class KeyGenerator {
    private KeyInfo keyInfo;
    // 每次缓存数据大小
    private static final int POOL_SIZE = 20;

    private static Map<String, KeyGenerator> keyMap = new HashMap<>(10);
    private KeyGenerator(String keyName){
        this.keyInfo = new KeyInfo(keyName, POOL_SIZE);
    }

    public static synchronized KeyGenerator getInstance(String keyName) {
        KeyGenerator keyGenerator;
        if (keyMap.containsKey(keyName)) {
            keyGenerator = keyMap.get(keyName);
        } else {
            keyGenerator = new KeyGenerator(keyName);
            keyMap.put(keyName, keyGenerator);
        }
        return keyGenerator;
    }

    // 委托给 KeyInfo 对象去获取nextKey值
    public int getNextKey(){
        return keyInfo.getNextKey();
    }

}
